// 检查更新
function updateChk(currInfo) {
	let _title = ''
	let _url = 'https://galaha.top/api/Appmgt/updateChk?appkey=scan2excel'
	uni.request({
		url: _url,
		method: 'get',
		success: (r) => {
			// console.log(r)
			if (r.data.code == 10000) {
				let svrInfo = r.data.data[0]
				checkVersionToLoadUpdate(svrInfo, currInfo)
			} else {
				// _title = r.data.msg
			}
		},
		fail: (e) => {
			console.log(e)
			_title = '无法连接更新服务器'
		},
		complete: () => {
			if (_title != '') {
				uni.showToast({
					title: _title,
					icon: 'none'
				})
			}
		}
	})
}
// 确定版本是否需要更新
function checkVersionToLoadUpdate(svrInfo, currInfo) {
	let s = plus.networkinfo.getCurrentType() == 3 ? 'wifi' : '移动'
	if (svrInfo.versionCode > currInfo.versionCode) {
		uni.showModal({
			title: '发现新版本v' + svrInfo.version,
			content: '当前为' + s + '网络，是否下载？',
			confirmText: '立即更新',
			success: function(res) {
				if (res.confirm) {
					appDownLoad(svrInfo.upUrl)
				} else if (res.cancel) {
					console.log('取消');
				}
			}
		})
	}
}
// 下载升级包
function appDownLoad(appUrl) {
	var dtask = plus.downloader.createDownload(
		appUrl, {
			filename: "_downloads/"
		},
		function(d, status) {
			// 下载完成
			if (status == 200) {
				plus.runtime.install(d.filename, {
					force: true
				}, function() {
					//进行重新启动;
					plus.runtime.restart();
				}, (e) => {
					uni.showToast({
						title: '升级包安装失败:' + JSON.stringify(e),
						icon: 'none'
					})
				});
			} else {
				uni.showToast({
					title: "升级包下载失败，错误码: " + status,
					icon: 'none'
				})
			}
		}
	)

	let view = new plus.nativeObj.View("maskView", {
		backgroundColor: "rgba(0,0,0,.6)",
		left: ((plus.screen.resolutionWidth / 2) - 50) + "px",
		bottom: "115px",
		width: "100px",
		height: "35px",
	})
	view.drawText('开始下载', {}, {
		size: '14px',
		color: '#FFFFFF'
	});
	view.show()
	dtask.addEventListener("statechanged", (e) => {
		if (e && e.downloadedSize > 0) {
			let jindu = ((e.downloadedSize / e.totalSize) * 100).toFixed(2)
			view.reset();
			view.drawText('已完成' + jindu + '%', {}, {
				size: '14px',
				color: '#FFFFFF'
			});
		}
	}, false);
	dtask.start();
}

export default {
	updateChk,
}
